/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;
import ru.miit.elearning.hibernate.dao.ConfigurationDAO;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.DocumentDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;

/**
 *
 * @author Cyclone
 */
public class EditCourseServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String message = null;

        Session session = null;
        Integer courseId = null;
        String title = null;
        try {

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            String act = request.getParameter("act");
            if (act != null) {
                courseId = Integer.parseInt(request.getParameter("courseId"));
                ConfigurationDAO configurationDAO = new ConfigurationDAO(session);
                if (act.equals("delProp")) {
                    int propertyId = Integer.parseInt(request.getParameter("propId"));
                    configurationDAO.deleteCurriculumProperty(courseId, propertyId);
                } else {
                    if (act.equals("addProp")) {
                        int propertyId = Integer.parseInt(request.getParameter("propId"));
                        configurationDAO.setCurriculumProperty(courseId, propertyId, null);
                    } else {
                        if (act.equals("editProp")) {
                            int propertyId = Integer.parseInt(request.getParameter("propId"));
                            String propertyValue = request.getParameter("propValue");
                            configurationDAO.setCurriculumProperty(courseId, propertyId, propertyValue);
                        }
                    }
                }
                act = null;
            } else {

                Integer directionId = null;
                String numberString = null;
                String description = null;

                FileItem fileItem = null;
                String attachTitle = null;

                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                if (!isMultipart) {
                    courseId = Integer.parseInt(request.getParameter("courseId"));
                    directionId = Integer.parseInt(request.getParameter("directionId"));
                    numberString = request.getParameter("number");
                    title = request.getParameter("title");
                    description = request.getParameter("description");
                } else {
                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items = upload.parseRequest(request);


                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            final String utf8 = "UTF-8";
                            if (courseId == null && item.getFieldName().equals("courseId")) {
                                courseId = Integer.parseInt(item.getString(utf8));
                                continue;
                            }
                            if (directionId == null && item.getFieldName().equals("directionId")) {
                                directionId = Integer.parseInt(item.getString(utf8));
                                continue;
                            }
                            if (description == null && item.getFieldName().equals("description")) {
                                description = item.getString(utf8);
                                continue;
                            }
                            if (numberString == null && item.getFieldName().equals("number")) {
                                numberString = item.getString(utf8);
                                continue;
                            }
                            if (title == null && item.getFieldName().equals("title")) {
                                title = item.getString(utf8);
                                continue;
                            }
                            if (attachTitle == null && item.getFieldName().equals("attachTitle")) {
                                attachTitle = item.getString(utf8);
                                continue;
                            }
                        } else {
                            fileItem = item;
                        }
                    }
                }


                CourseDAO courseDAO = new CourseDAO(session);
                Integer number = null;
                if(numberString != null && numberString.length() > 0)
                try {
                    number = Integer.parseInt(numberString);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                courseDAO.updateCurriculumLevel(courseId, directionId, number, title, description);

                if (fileItem != null) {
                    DocumentDAO documentDAO = new DocumentDAO(session);
                    Integer docId = documentDAO.addCurriculumDocument(courseId, ( (attachTitle != null && attachTitle.length() > 0) ? attachTitle : fileItem.getName()));
                    documentDAO.addDocumentVersion(docId, null, fileItem.getInputStream(), documentDAO.findUserIdByLogin(request.getRemoteUser()), fileItem.getName(), fileItem.getContentType(), null);
                }
            }

            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }
            message = "Курс " + (title != null ? "\"" + title + "\" " : "") + "отредактирован";

            getServletContext().setAttribute("message", message);
            if (courseId != -1) {
                response.sendRedirect("Course?id=" + courseId);
            } else {
                response.sendRedirect("Courses");
            }
        } catch (ConstraintViolationException e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }

            /*
            if (e.getConstraintName().equals("unique_curriculum_level_numeral")) {
            message = "Курс с таким номером уже существует в данном направлении";
            } else {
            message = "Нарушена одна из зависимостей";
            }
             */

            message = "Нарушена одна из зависимостей. Возможно, выбранный номер занят другим курсом.<br/>Оставьте номер пустым для автоопределения.";
            e.printStackTrace();

            if (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

            getServletContext().setAttribute("message", message);
            if (courseId != -1) {
                response.sendRedirect("Course?id=" + courseId);
            } else {
                response.sendRedirect("Courses");
            }
        } catch (Exception e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            message = "Ошибка запроса описания курса";
            e.printStackTrace();

            getServletContext().setAttribute("message", message);

            if (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }

            if (courseId != -1) {
                response.sendRedirect("Course?id=" + courseId);
            } else {
                response.sendRedirect("Courses");
            }
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
